#include <time.h>


typedef void (*logprintf_t)(const char* format, ...);

static logprintf_t logprintf;
static void **ppPluginData;
extern void *pAMXFunctions;


//----------------------------------------------------------
// The AmxLoad() function gets called when a new gamemode or
// filterscript gets loaded with the server. In here we register
// the native functions we like to add to the scripts.

PLUGIN_EXPORT int PLUGIN_CALL AmxLoad( AMX *amx )
{

	struct amx_info_t amx_info;
	amx_info.file = amx;

	int tmp;
	if(amx_FindPublic(amx, "OnPlayerCommandText", &tmp) == AMX_ERR_NONE)
		amx_info.onplayercmd_idx = tmp;
	else
		amx_info.onplayercmd_idx = -1;

	amx_list.push_back(amx_info);
	
	int res = amx_Register( amx, natives, -1 );

	AMX_HEADER *hdr = reinterpret_cast<AMX_HEADER*>(amx->base);

	AMX_FUNCSTUBNT *nat = reinterpret_cast<AMX_FUNCSTUBNT*>(hdr->natives + reinterpret_cast<unsigned int>(amx->base));
	AMX_FUNCSTUBNT *lib = reinterpret_cast<AMX_FUNCSTUBNT*>(hdr->libraries + reinterpret_cast<unsigned int>(amx->base));

	for (AMX_FUNCSTUBNT *n = nat; n < lib; ++n)
	{
	  if (n->address == 0) 
	  {
	    char *name = reinterpret_cast<char*>(n->nameofs + reinterpret_cast<unsigned int>(hdr));
	    logprintf("Error: Function '%s' is not registered in %p", name, amx);
	  }
	}

	
	return res;
}

//----------------------------------------------------------
// When a gamemode is over or a filterscript gets unloaded, this
// function gets called. No special actions needed in here.

PLUGIN_EXPORT int PLUGIN_CALL AmxUnload( AMX *amx )
{
	for (amx_list_t::iterator it = amx_list.begin(), end = amx_list.end(); it != end; it++)
	{
		if ((*it).file == amx)
		{
			amx_list.erase(it);
			break;
		}
	}
	return AMX_ERR_NONE;
}

//----------------------------------------------------------
// The Support() function indicates what possibilities this
// plugin has. The SUPPORTS_VERSION flag is required to check
// for compatibility with the server.

PLUGIN_EXPORT unsigned int PLUGIN_CALL Supports()
{
	return SUPPORTS_VERSION | SUPPORTS_AMX_NATIVES;
}

//----------------------------------------------------------
// The Load() function gets passed on exported functions from
// the SA-MP Server, like the AMX Functions and logprintf().
// Should return true if loading the plugin has succeeded.

PLUGIN_EXPORT bool PLUGIN_CALL Load( void **ppData )
{
	pAMXFunctions = ppData[PLUGIN_DATA_AMX_EXPORTS];
	logprintf = (logprintf_t)ppData[PLUGIN_DATA_LOGPRINTF];

	/*
	for(int i=0; i < MAX_AMX_AMOUNT; i++)
	{
		amxmodule[i] = (AMX *) NULL;
		onplayercmd_idx[i] = -1;
	}
	*/
	srand(time(NULL));


	logprintf("  Plugin myfuncs got loaded. Version: " __DATE__ ",  " __TIME__ );

	return true;
}

//----------------------------------------------------------
// The Unload() function is called when the server shuts down,
// meaning this plugin gets shut down with it.

PLUGIN_EXPORT void PLUGIN_CALL Unload( )
{
	logprintf( "  Plugin myfuncs got unloaded." );
}
